package com.apes.scm.sal.saleReturn;

import com.apes.framework.api.SpringManager;
import com.apes.framework.jpa.DefaultPersistListener;
import com.apes.framework.jpa.Model;
import com.apes.framework.jpa.comment.Comment;
import com.apes.framework.jpa.generator.ApesGenerator;
import com.apes.framework.plugin.soe.annotations.State;
import com.apes.framework.plugin.soe.annotations.States;
import com.apes.framework.plugin.soe.metadata.BusinessAttributeValue;
import com.apes.framework.util.ApesConst;
import com.apes.framework.util.LogicalUtil;
import com.apes.scm.account.account.model.Cooperation;
import com.apes.scm.contract.model.Contract;
import com.apes.scm.masterdata.enumeration.model.Enumeration;
import com.apes.scm.masterdata.frame.model.Dept;
import com.apes.scm.masterdata.party.model.PartyRole;
import com.apes.scm.masterdata.party.repository.PartyRoleRepository;
import com.apes.scm.masterdata.stock.model.Location;
import com.apes.scm.sal.saleOrder.SaleOrder;
import com.apes.scm.sal.saleOrder.SaleOrderItem;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate;
import org.hibernate.annotations.SelectBeforeUpdate;

import javax.persistence.*;
import javax.validation.constraints.NotNull;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 功能：分销退货
 *
 * @author xul
 * @create 2018-01-25 19:36
 */
@Getter
@Setter
@SelectBeforeUpdate
@DynamicInsert
@DynamicUpdate
@Entity
@EntityListeners(DefaultPersistListener.class)
@Table(name = SaleReturn.CONST_TABLE_NAME)
public class SaleReturn extends Model {
    public static final String CONST_TABLE_NAME = "sale_return";

    @Id
    @Column(name = "id")
    @ApesGenerator(code = CONST_TABLE_NAME, name = "销售退回", prefix = "%(yy)%(month)", padding = 4, useDateRange=true)
    private String id;

    @States(name = "订单类型", values = {
            @State(id = "A", name = "有原单退货"),
            @State(id = "B", name = "无原单退货")})
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "order_type", referencedColumnName = "id", nullable = false)
    private BusinessAttributeValue orderType;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "move_type", referencedColumnName = "id")
    private Enumeration moveType; //交货方式：("direct", "部分交货"), ("one", "一次性交货");

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "company_id", referencedColumnName = "id", nullable = false)
    @Comment("公司")
    private PartyRole company;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "dept_id", referencedColumnName = "id", nullable = false)
    @Comment("部门")
    private Dept dept;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "clerk_id", referencedColumnName = "id")
    @Comment("业务员")
    private PartyRole clerk;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "contract_id", referencedColumnName = "id")
    @Comment("合同号")
    private Contract contract;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "customer_id", referencedColumnName = "id", nullable = false)
    @Comment("客户")
    private PartyRole customer;

    @NotNull
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "location_id", referencedColumnName = "id")
    @Comment("库存位置")
    private Location location;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name="sale_id", referencedColumnName="id")
    @Comment("原订单")
    private SaleOrder saleOrder;

    @Column(name = "origin", length = 30)
    @Comment("源单据")
    private String origin;

    @Column(name = "remark", length = 120)
    @Comment("订单备注")
    private String remark;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "return_reasons", referencedColumnName = "id")
    @Comment("退货原因")
    private Enumeration returnReasons;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "cooperation_id", referencedColumnName = "id", nullable = false)
    @Comment("合作方式")
    private Cooperation cooperation;

    @Column(name = "date_approve")
    @Comment("审批日期")
    private Date dateApprove;

    @Column(name = "date_done")
    @Comment("审批日期")
    private Date dateDone;

    @Column(name = "date_planned")
    @Comment("计划日期")
    private Date datePlanned;



    @Column(name = "date_cancel")
    @Comment("取消日期")
    private Date dateCancel;

    @States(name = "订单状态", values = {
            @State(id = "sent", name = "退货申请"),
            @State(id = "confirmed", name = "审核"),
            @State(id = "done", name = "已完成")})
    @Column(name = "state", length = 10, nullable = false)
    private String state = "sent";

    @Column(name = "is_shipped", nullable = false)
    @Comment("已交货")
    private boolean shipped = false;

    @Column(name = "invoice_status", length = 10, nullable = false)
    @Comment("开票状态")
    private String invoiceStatus = "no"; //账单状态: ("no", "没有开票"), ("to_invoice", "开票中"), ("invoiced", "开票完成")

    @Column(name = "amt_tax", nullable = false, columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("税金")
    private double amtTax = 0;

    @Column(name = "amt_untaxed", nullable = false, columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("不含税金额")
    private double amtUntaxed = 0;

    @Column(name = "amt_total", nullable = false, columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("总计")
    private double amtTotal = 0;

    @Column(name = "discount", nullable = false, columnDefinition = ApesConst.FIELD_16_4)
    @Comment("折扣（返利）金额")
    private double discount = 0;

    @Comment("会员扩展信息编码")
    @Column(name = "customer_expand_id", length = 32)
    private String FnCustomerExpandId;

    @OneToMany(mappedBy = "saleReturn", cascade = CascadeType.ALL, orphanRemoval = true)
    private Set<SaleReturnItem> saleReturnItems = new HashSet(); //订单行

    public Set<SaleReturnItem> getSaleReturnItems() {
        for (SaleReturnItem item : saleReturnItems) {
            // 筛选数量为零的行
            if(item.getProductUomQty() == 0) {
                saleReturnItems.remove(item);
                continue;
            }
            item.setSaleReturn(this);
            item.setCompany(company);

        }
        return saleReturnItems;
    }



    public void computeAmt() {
        // 赋予初始值
        amtUntaxed = 0; amtTax = 0; discount = 0;
        for (SaleReturnItem item : saleReturnItems) {
            item.computeAmt();
            amtUntaxed += item.getPriceSubtotal();
            amtTax += item.getPriceTax();
            discount += item.getDiscount();
        }
        amtTotal = amtUntaxed + amtTax;
    }

    public void computeDiscount() {
        for (SaleReturnItem item : saleReturnItems) {
            SaleOrderItem saleOrderItem = item.getSaleOrderItem();
            if( saleOrderItem.getQtyReturned() + item.getProductUomQty() == saleOrderItem.getProductUomQty() ){
                // 设置为余下值
                item.setDiscount(saleOrderItem.getDiscount() - saleOrderItem.getDiscount() / saleOrderItem.getProductUomQty() * saleOrderItem.getQtyReturned());
            } else {
                // 设置为平均值 * 退货数量
                item.setDiscount(saleOrderItem.getDiscount() / saleOrderItem.getProductUomQty() * item.getProductUomQty());
            }
        }
    }


    /**
     * 功能：设置订单交货状态
     */
    public void setShipped() {
        // 不存在退回冲红明细 或者 退货冲红数量等于收货数量（消耗商品）
        long result = getSaleReturnItems().stream()
                .filter(item -> item.getQtyDelivered() > 0 && LogicalUtil.notIn(item.getProduct().getType(), "aut"))
                .filter(item -> item.getQtyDelivered() > item.getQtyDeliver())
                .count();
        if (result == 0) {
            setShipped(true);
            setState();
        }
    }

    /**
     * 功能：设置订单状态
     */
    public void setState() {
        if (!state.equals("confirmed")) return;
        if(!shipped) return;

        setDateDone(new Date());
        setState("done");

        // 有单退货需减少占款未清项
        if (orderType.getCode().equals("A")) {
            SpringManager.getBean(SaleReturnWithOrderService.class).done(this); // 执行完成时所需的操作
        }
    }

    /***
     * 功能: 判断当前单据是否需要收货
     */
    @Transient
    @States(name = "需要收货", values = {
            @State(id = "yes", name = "需收货"),
            @State(id = "no", name = "无需收货")})
    private String needShip;

    public String getNeedShip() {
        Set<SaleReturnItem> saleReturnItems = this.saleReturnItems.stream()
                .filter(saleReturnItem -> LogicalUtil.notIn(saleReturnItem.getProduct().getType(), "aut") && saleReturnItem.getQtyDelivered() > 0)
                .collect(Collectors.toSet());
        return saleReturnItems.isEmpty() ? "no" : "yes";
    }

    @Transient
    private PartyRole _creator;

    public PartyRole get_creator() {
        if(this.getCreator() == null) return null;
        return SpringManager.getBean(PartyRoleRepository.class).findOne(this.getCreator());
    }

    @Transient
    private String saleOrderType;

    public String getSaleOrderType(){
        if (this.saleOrder == null) return "";
        return this.saleOrder.getOrderType();
    }
}
